﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
	
	<script type="text/javascript" src="https://www.google.com/jsapi"></script>
	<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="Matrix.js"></script>
	
</head>
<body>

    <script type="text/javascript">

	
		google.load("visualization", "1", {packages:["corechart"]});
		google.setOnLoadCallback(drawChart);

		$(function () {
		    $('#points').val('0;1000\n1;900\n2;500\n3;500\n4;270\n5;300\n6;100');
		});

		function drawChart(data) {
			var data = google.visualization.arrayToDataTable(data);

			var options = {
			    title: 'Points',
			    width: 500,
			    height: 500,
			    hAxis: { title: 'X' },
			    vAxis: { title: 'Y' },
                legend: 'none'
			};
		
			var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
			chart.draw(data, options);
		}
		
		function getPoints() {
			var lines = $("textarea#points").val().split(/\n/);
			var points = [];
			var point;
			
			for (var i=0; i < lines.length; i++) {
				point = lines[i].split(';');
				points[i] = new Array(parseInt(point[0]), parseInt(point[1]));
			}
			
			return points;
		}
		
		function getX(points) {
			var x = [];
			
			for (var i=0; i < points.length; i++) {
				x[i] = new Array(points[i][0], 1);
			}
			
			return x;
		}
		
		function getY(points) {
		    var y = [];

		    for (var i = 0; i < points.length; i++) {
		        y[i] = [points[i][1]];
			}
			
			return y;
		}
		
		function draw() {
		    var points = getPoints();

		    var XPoints = getX(points);

		    var X = new Matrix(XPoints);

		    var XTrans = X.transpose();

		    var XXTrans = Matrix.multiply(XTrans, X);

		    var XXTransInv = XXTrans.inverse();

		    var XXTransInvXTrans = Matrix.multiply(XXTransInv, XTrans);

		    var YPoints = getY(points);

		    var Y = new Matrix(YPoints);

		    var beta = Matrix.multiply(XXTransInvXTrans, Y);

		    var Xbeta = Matrix.multiply(X, beta);
		    
			data = [];
			data[0] = new Array('X', 'Y', 'predictY');
			for (var i=0; i < points.length; i++) {
				data[i + 1] = new Array(points[i][0], points[i][1], null);
            }

            var k = data.length;
            for (var i=0, k=data.length; i < Xbeta.values.length; i++, k++) {
			    data[k] = new Array(points[i][0], null, Xbeta.values[i][0] );
            }

			drawChart(data);
		}

    </script>
	<div id="points_container">
		<textarea id="points" rows="10" cols="10"></textarea>
		<button type="button" onclick="draw()">Draw</button>
	</div>
	<div id="chart_div"></div>
</body>
</html>
